import type { GreasyForkElements } from '../../../../../../../../types/constants/personalization/greasy_fork'
import { ThemeVarService } from '../../../../../../../../lib/abstract/style/theme_var/service'
import { ICON_IDS } from '../../../../../../../../lib/icons/types/constants'
import { PageHandler } from '../../../../../../../../lib/page_handler'
import { ToolKit } from '../../../../../../../../lib/utils/toolkit'
import {
  BodyClasses,
  PAGE_ELEMENTS,
  PROJECT_PREFIX,
  SUPPORTED_PLATFORMS,
} from '../../../../../../../../types/constants'
import { StylesService } from '../../../../../../../../types/constants/styles'
import { CommonPage } from './common'

const ACTION_STYLES: Record<string, { bg: string, text?: string, label: string, value: string }> = {
  ban: { bg: 'linear-gradient(135deg, #FF5252, #FF1744)', label: '封禁', value: 'ban' },
  deleteAndLock: { bg: 'linear-gradient(135deg, #FF9800, #FF5722)', label: '删除并锁定', value: 'deleteAndLock' },
  restore: { bg: 'linear-gradient(135deg, #4CAF50, #8BC34A)', label: '撤销删除', value: 'restore' },
}

export class ModeratorActionsPage {
  elements: GreasyForkElements = PAGE_ELEMENTS[SUPPORTED_PLATFORMS.GREASY_FORK]
  private static instance: ModeratorActionsPage
  private readonly pageHandler: PageHandler = PageHandler.getInstance()
  private readonly commonPage: CommonPage = CommonPage.getInstance()
  protected readonly themeVarService: ThemeVarService = ThemeVarService.getInstance()
  private readonly stylesService: StylesService = StylesService.getInstance()
  private tableSelector: string = 'table'

  /**
   * 获取单例实例
   */
  public static getInstance(): ModeratorActionsPage {
    if (!ModeratorActionsPage.instance) {
      ModeratorActionsPage.instance = new ModeratorActionsPage()
    }
    return ModeratorActionsPage.instance
  }

  init(): void {
    ToolKit.ui.table.addClassToTableColumn(['时间', '管理员', '操作'], BodyClasses.NO_WRAP, this.tableSelector)
    this.styleProjectCells()
    this.styleActionCells()
  }

  /**
   * 美化项目列单元格
   */
  private styleProjectCells(): void {
    const actionColumnIndexes = ToolKit.ui.table.getColumnIndexes('项目', this.tableSelector)

    if (!actionColumnIndexes)
      return

    $(`${this.tableSelector} tr`).each((_, row) => {
      const $row = $(row)
      const $actionCell = $row.find(`td:nth-child(${actionColumnIndexes[0] + 1})`)

      this.addProjectTypeIcon($actionCell)
    })
  }

  /**
   * 美化操作列单元格
   */
  private styleActionCells(): void {
    const actionColumnIndexes = ToolKit.ui.table.getColumnIndexes('操作', this.tableSelector)

    if (!actionColumnIndexes)
      return

    $(`${this.tableSelector} tr`).each((_, row) => {
      const $row = $(row)
      const $actionCell = $row.find(`td:nth-child(${actionColumnIndexes[0] + 1})`)
      const actionText = $actionCell.text().trim()
      const actionType = this.getActionType(actionText)

      // 移除原有文本
      $actionCell.empty()

      // 添加徽章
      if (actionType.length === 0)
        return

      this.pageHandler.features.badge.addBadge($actionCell, 'deal-result', actionText, { backgroundColor: ACTION_STYLES[actionType].bg })
    })
  }

  /**
   * 获取项目类型
   */
  addProjectTypeIcon($cell: JQuery): void {
    // 1. 获取单元格内容特征
    const $link = $cell.find('a')
    const hasUserClass = $link.hasClass('user-link')
    const isDeletedUser = $cell.find('i').length > 0
    const isDeletedScript = $cell.children().length === 0

    // 2. 确定项目类型
    const projectType = isDeletedUser
      ? 'deleted-user'
      : isDeletedScript
        ? 'deleted-script'
        : hasUserClass
          ? 'user'
          : $link.length ? 'script' : null

    if (!projectType)
      return

    // 3. 特殊处理各类型
    switch (projectType) {
      case 'deleted-user':
        this.styleDeletedUser($cell)
        break
      case 'deleted-script':
        this.styleDeletedScript($cell)
        break
      case 'user':
        this.styleUserProject($cell)
        break
      case 'script':
        this.styleScriptProject($cell)
        break
    }
  }

  /**
   * 处理已删除用户样式
   */
  private styleDeletedUser($cell: JQuery): void {
    const $icon = $cell.find('i')
    const text = $icon.text().trim()

    // 提取用户ID (匹配数字部分)
    const userIdMatch = text.match(/\d+/)
    const newText = userIdMatch ? `id ${userIdMatch[0]}` : '未知 id'

    $icon.addClass('project-type__deleted-user')
    $icon.text(`[已注销] ${newText}`)
    $cell.html($cell.html().replace(/用户：/g, ''))
  }

  /**
   * 处理已删除脚本样式
   */
  private styleDeletedScript($cell: JQuery): void {
    const text = $cell.text().trim()

    // 提取脚本ID (匹配数字部分)
    const scriptIdMatch = text.match(/\d+/)
    const newText = scriptIdMatch ? `id ${scriptIdMatch[0]}` : '未知 id'

    $cell.addClass('project-type__deleted-script')
    $cell.text(`[已删除] ${newText}`)
  }

  /**
   * 处理用户项目样式
   */
  private styleUserProject($cell: JQuery): void {
    $cell.find('a')
      .addClass('project-type__user-link')
    $cell.html($cell.html().replace(/用户：/g, ''))
  }

  /**
   * 处理脚本项目样式
   */
  private styleScriptProject($cell: JQuery): void {
    $cell.find('a')
      .addClass('project-type__script-link')
    $cell.html($cell.html().replace(/脚本：/g, ''))
  }

  /**
   * 获取操作类型
   */
  getActionType(label: string): string {
    const styles = Object.values(ACTION_STYLES)
      .find(item => label === item.label)

    if (styles)
      return styles.value

    return ''
  }

  getMainStyles(): string {
    return `
table.text-content {
  background-color: var(--${PROJECT_PREFIX}-theme-bg-base) !important;
  border: none !important;
  box-shadow: none !important;
  margin: 0 !important;
  
  tr {
    td {
      padding: 10px 5px !important;
      
      .project-type__deleted-user,
      &.project-type__deleted-script {
        font-style: italic
      }
      
      .project-type__deleted-user::before {
 
        ${this.stylesService.inlinePseudo.icon({ backgroundImageId: ICON_IDS.auth.logout })}
      }
      &.project-type__deleted-script::before {
        ${this.stylesService.inlinePseudo.icon({ backgroundImageId: ICON_IDS.link.linkExpired })}
      }
      .project-type__user-link::before {
        ${this.stylesService.inlinePseudo.icon({ backgroundImageId: ICON_IDS.role.author })}
      }
      .project-type__script-link::before {
        ${this.stylesService.inlinePseudo.icon({ backgroundImageId: ICON_IDS.link.link })}
      }
    }
  }
  
  a {
    ${this.commonPage.linkStyles()}
  }
}
`
  }
}
